const Router = require('koa-router')
const router = new Router();
const Koa = require('koa2');
const core = require('koa2-cors')
const path =require("path")
const jwt = require("jsonwebtoken")
const { returnMsg, queryFn ,jwtVerify} = require("../../config")
const multer = require("@koa/multer")

// 存储文件的名称
let myfilename = ""


const app = new Koa();

var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname ,'/upload/'))
    },
    //修改文件名称
    filename: function (req, file, cb) {
        let type = file.originalname.split('.')[1]
        // logo.png -> logo.xxx.png
        myfilename = `${file.fieldname}-${Date.now().toString(16)}.${type}`
        cb(null, myfilename)
    }
})

//文件上传限制
const limits = {
    fields: 1,//非文件字段的数量
    fileSize: 200 * 1024,//文件大小 单位 b 200kb    
    files: 1//文件数量
}

let upload = multer({storage,limits})

//解决跨域问题
// app.use(core())
router.post('/', upload.single('avatar'),async ctx => {
    // 绕开鉴权
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, "查询用户失败","token已过期或该用户不存在")
        return;
    }
    let sql = `update user set avatar = '${myfilename}' where token = '${token}'`
    let result =  await queryFn(sql)
    let sql2 = `select username,avatar,token from user where token='${token}'`
    let result2 =  await queryFn(sql2)
    // ctx.body = returnMsg(0, "修改成功",result2[0])
    ctx.body = returnMsg(0, "修改成功",{
        avatar:result2[0].avatar,
        username:result2[0].username,
        'cms-token':result2[0].token,
    })
})

module.exports = router;